package com.canbot.u05.activity.shoppingGuide.sales;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.ChoosePicActivity;
import com.canbot.u05.bean.sales.RouteGuide;
import com.canbot.u05.glide.GlideApp;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.update.StringUtils;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;
import com.canbot.u05.widget.RoundImageView;

import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 导购路线指引添加路线界面
 */
public class AddRouteActivity extends BaseActivityNoTitle {

        private RelativeLayout chooseMap;

        //选择底图的请求码
        private static final int REQUESTCODEMAP = 111;

        private RoundImageView ivSamllIcon;

        private android.widget.EditText ettitle;

        private android.widget.EditText etaddress;

        private String pic;

        private android.widget.TextView tvheadtitle;

        private android.widget.Button btnback;

        private android.widget.TextView tvtitle;

        private android.widget.TextView tvaddress;

        private ImageView ivsmallicon;

        private RelativeLayout rlchoosemap;

        private android.widget.Button btnnext;

        private android.widget.Button btncomplete;

        private String title;

        private String address;

        // private int id;
        private String id;

        private static final int HEAD_EDIT_ADDRESS_SUCCESS = 101;

        private static final int HEAD_EDIT_ADDRESS_FAILURE = 102;

        private Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                                case HEAD_EDIT_ADDRESS_SUCCESS:
                                        updateDataChest();

                                        break;
                                case HEAD_EDIT_ADDRESS_FAILURE:
                                        break;
                        }
                }
        };

        private ImageView mHint;

        private List<RouteGuide> routeList;

        private String editText;

        private static final int TIMEOUT = 100;//超时时间100s

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_add_route);
                initView();
                initEvent();

        }

        @Override
        protected void onResume() {
                super.onResume();
//                MsgSendUtils.sendStringMsg(MsgType.SENT_PAD_ENTER_ROUTE_SETUP_ADDRESS,"enter route address");
        }

        @Override
        protected void onDestroy() {
                super.onDestroy();
                title = "";
                pic = "";
                address = "";
        }

        private void initEvent() {

                ettitle.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                        }

                        @Override
                        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                                String editText = charSequence.toString();
                                if(routeList == null){
                                        return;
                                }
                                for (RouteGuide routeGuide : routeList) {
                                        String title = routeGuide.getTitle();
                                        Logger.d("AddRouteActivity", editText + ",--," + title);
                                        if (title.equals(editText)) {
                                                mHint.setVisibility(View.VISIBLE);
                                                break;
                                        }
                                        else {
                                                mHint.setVisibility(View.GONE);
                                        }
                                }
                                if (editText.length() > 8) {
                                        ToastTools.newInstance(AddRouteActivity.this).showText(getString(R.string.input_up_words3));
                                }
                        }

                        @Override
                        public void afterTextChanged(Editable editable) {

                        }
                });
                //选择底图
                chooseMap.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                                Intent intent = new Intent(AddRouteActivity.this, ChoosePicActivity.class);
                                if (!TextUtils.isEmpty(pic)){
                                        intent.putExtra("pic",pic);
                                }
                                startActivityForResult(intent, REQUESTCODEMAP);
                                overridePendingTransition(R.anim.face_zoom_enter,
                                        R.anim.face_zoom_exit);
                        }
                });

        }

        private void initView() {
                chooseMap = (RelativeLayout) findViewById(R.id.rl_choose_map);
                ivSamllIcon = (RoundImageView) findViewById(R.id.iv_small_icon);
                this.ettitle = (EditText) findViewById(R.id.et_title);
                this.etaddress = (EditText) findViewById(R.id.et_address);
                this.btncomplete = (Button) findViewById(R.id.btn_complete);
                this.btnnext = (Button) findViewById(R.id.btn_next);
                mHint = (ImageView) findViewById(R.id.address_ensure);

                Intent intent = getIntent();
                String info = intent.getStringExtra("info");
                String edit = intent.getStringExtra("edit");
                //id = intent.getIntExtra("id", -1);
                id = intent.getStringExtra("id");

                if ("address".equals(edit)) {
                        btnnext.setVisibility(View.GONE);
                        btncomplete.setVisibility(View.VISIBLE);
                        String title = intent.getStringExtra("title");
                        String address = intent.getStringExtra("address");
                        String pic = intent.getStringExtra("pic");
                        this.title = title;
                        this.address = address;
                        this.pic = pic;
                        ettitle.setText(title + "");
                        etaddress.setText(address + "");

                }
                else {
                        btnnext.setVisibility(View.VISIBLE);
                        btncomplete.setVisibility(View.GONE);
                }
                routeList = JSON.parseArray(info, RouteGuide.class);
                Logger.d("AddRouteActivity", "routeList:" + routeList);

        }

        /**
         * 返回
         *
         * @param view
         */
        public void back(View view) {
                finish();
                overridePendingTransition(R.anim.face_zoom_enter,
                        R.anim.face_zoom_exit);
        }

        /**
         * 下一步操作(添加的时候)
         *
         * @param view
         */
        public void next(View view) {
                title = ettitle.getText().toString();
                address = etaddress.getText().toString();
                if (StringUtils.isEmpty(title) || StringUtils.isEmpty(address) || StringUtils.isEmpty(pic)) {
                        ToastTools.newInstance(this).showText(getString(R.string.content_empty));
                        return;

                }

                Intent intent = new Intent(this, SpeechSetupActivity.class);
                intent.putExtra("title", title);
                intent.putExtra("address", address);
                intent.putExtra("pic", pic);



                        finish();
                        startActivity(intent);
                        overridePendingTransition(R.anim.face_zoom_enter,
                                R.anim.face_zoom_exit);



        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);

                if (requestCode == REQUESTCODEMAP && resultCode == RESULT_OK) {
                        Bundle path = data.getBundleExtra("path");
                        pic = path.getString("pic");
                        Logger.d("AddRouteActivity", pic);
                        GlideApp.with(this)
                                .asDrawable()
                                .load(IpMsgConst.HTTP_URL_CHEST + pic.replace("/uupic/","/uupic_thumb/"))
                                .thumbnail(0.1f)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                                .skipMemoryCache(false)
                                .placeholder(R.drawable.sales_banner01)//占位图
                                .error(R.drawable.ic_picture_loadfailed)
                                .override(100, 100)
                                .into(ivSamllIcon);
                }
        }

        private Dialog dialogLoading;

        /**
         * 编辑完成
         *
         * @param view
         */
        public void complete(View view) {

                updateDataChest();


        }


        private void updateDataChest() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.updating));
                title = ettitle.getText().toString();
                address = etaddress.getText().toString();
                if (StringUtils.isEmpty(title) || StringUtils.isEmpty(address)) {
                        ToastTools.newInstance(this).showText(getString(R.string.content_empty));
                        return;
                }
                RouteGuide routeGuide = new RouteGuide();
                routeGuide.setId(id);
                routeGuide.setPic(pic);
                routeGuide.setTitle(title);
                routeGuide.setAddress(address);
                String s = JSON.toJSONString(routeGuide);

                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.SOCKET_HOST2 + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                Call<String> stringCall = salesApi.editAddressInfo(s);
                stringCall.enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                String result = response.body();
                                Logger.d("AddRouteActivity", "修改地址返回结果；" + result);
                                if ("0".equals(result)) {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                        ToastTools.newInstance(AddRouteActivity.this).showText(getString(R.string.modify_successfully));
                                        finish();
                                        overridePendingTransition(R.anim.face_zoom_enter,
                                                R.anim.face_zoom_exit);

                                }
                                else {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                        ToastTools.newInstance(AddRouteActivity.this).showText(getString(R.string.modify_failed));
                                        finish();
                                        overridePendingTransition(R.anim.face_zoom_enter,
                                                R.anim.face_zoom_exit);
                                }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                ToastTools.newInstance(AddRouteActivity.this).showText(getString(R.string.modify_failed));
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter,
                                        R.anim.face_zoom_exit);
                        }
                });
        }

        /**
         * 设置超时
         * @return
         */
        private OkHttpClient setTimeOut(){
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }

}
